const { getUserData } = require('../../model/user');
const config = require('../../utils/config');
import { apiRequest } from '../_utils/apiRequest';
const addressManager = require('../../model/address');

export const getUserAddresses = () => {
  const user = getUserData();

  if (!user.info.id) {
    return Promise.reject(new Error('用户未登录或未获取到用户信息'));
  }

  return apiRequest({
    url: `${config.backendApiUrl}/users/me/addresses`,
    method: 'GET',
  });
};

export const addAddress = async (address) =>  {
  const user = getUserData();

  if (!user.info.id) {
    return Promise.reject(new Error('用户未登录或未获取到用户信息'));
  }

  try {
    // 向服务器添加地址
    const data = await apiRequest({
      url: `${config.backendApiUrl}/users/me/addresses`,
      method: 'POST',
      data: address,
    });

    // 更新本地缓存
    addressManager.updateAddress(data.id, { ...address, id: data.id });

    return data;
  } catch (error) {
    console.error('Failed to add address:', error);
    throw error;
  }
};

export const updateAddress = async (addressId, address) => {
  try {
    // 向服务器更新地址
    await apiRequest({
      url: `${config.backendApiUrl}/addresses/me/${addressId}`,
      method: 'PUT',
      data: address,
    });

    // 更新本地缓存
    addressManager.updateAddress(addressId, address);
  } catch (error) {
    console.error('Failed to update address:', error);
    throw error;
  }
};

export const getAddressById = async (addressId) => {
  return apiRequest({
    url: `${config.backendApiUrl}/addresses/me/${addressId}`,
    method: 'GET',
  });
};

export const deleteAddress = async (addressId) => {
  try {
    // 向服务器删除地址
    await apiRequest({
      url: `${config.backendApiUrl}/addresses/me/${addressId}`,
      method: 'DELETE',
    });

    // 从本地缓存中删除地址
    addressManager.deleteAddress(addressId);
  } catch (error) {
    console.error('Failed to delete address:', error);
    throw error;
  }
};
module.exports = { getUserAddresses, addAddress, getAddressById, updateAddress, deleteAddress };
